package com.mpgame.database.mysql.utils;

import com.mpgame.database.mysql.config.MySqlCfg;
import com.mpgame.utils.Log;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

public class MyBatisUtil {
    private static final Map<String, SqlSessionFactory> sessionFactories = new ConcurrentHashMap<>();
    private static final Map<String, Boolean> initializedDatabases = new ConcurrentHashMap<>();
    
    public static void init(MySqlCfg config, String databaseName) {
        if (initializedDatabases.getOrDefault(databaseName, false)) {
            Log.warn("MyBatis " + databaseName + " 已初始化，不可重复初始化！");
            return;
        }
        
        try {
            // 使用代码方式创建SqlSessionFactory，不需要XML配置文件
            Environment environment = new Environment(
                "development",
                new JdbcTransactionFactory(),
                DataSourceUtil.getDataSource(databaseName)
            );
            
            org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration(environment);
            
            // 配置MyBatis
            configuration.setMapUnderscoreToCamelCase(true);
            configuration.setLogImpl(org.apache.ibatis.logging.nologging.NoLoggingImpl.class);
            
            // 添加Mapper包扫描
            configuration.addMappers("com.mpgame.database.mysql.mapper");
            
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            SqlSessionFactory factory = builder.build(configuration);
            
            sessionFactories.put(databaseName, factory);
            initializedDatabases.put(databaseName, true);
            
            Log.info("MyBatis " + databaseName + " 初始化成功");
        } catch (Exception e) {
            Log.err("MyBatis " + databaseName + " 初始化失败: " + e.getMessage());
            throw new RuntimeException("MyBatis " + databaseName + " 初始化失败", e);
        }
    }
    /** 默认使用game数据库 */
    public static SqlSession getSqlSession() {
        return getSqlSession("game");
    }
    
    public static SqlSession getSqlSession(String databaseName) {
        if (!initializedDatabases.getOrDefault(databaseName, false)) {
            throw new RuntimeException("MyBatis " + databaseName + " 未初始化，请先调用init方法");
        }
        
        SqlSessionFactory factory = sessionFactories.get(databaseName);
        if (factory == null) {
            throw new RuntimeException("MyBatis " + databaseName + " 会话工厂未找到");
        }
        
        return factory.openSession();
    }
    
    public static void close() {
        sessionFactories.clear();
        initializedDatabases.clear();
        Log.info("所有MyBatis会话工厂已关闭");
    }
}